# flake8: noqa
# from vnpy.app.paper_account import PaperAccountApp
from vnpy.app.ding_messager import DingMsgApp
from vnpy.app.data_recorder import DataRecorderApp
from vnpy.app.data_manager import DataManagerApp
from vnpy.event import EventEngine

from vnpy.trader.engine import MainEngine
from vnpy.trader.ui import MainWindow, create_qapp
from vnpy.trader.object import SubscribeRequest, Exchange

# from vnpy.gateway.ctp6.4 import CtpGateway4
# from vnpy.gateway.ctp6.5 import CtpGateway5
# from vnpy.gateway.ctp6.9 import CtpGateway9
from vnpy.gateway.ctp import CtpGateway
from vnpy.trader.event import EVENT_TICK, EVENT_BAR, EVENT_LOG , EVENT_CONTRACT, EVENT_ACCOUNT, EVENT_ORDER, EVENT_TRADE, EVENT_ORDER_OP, EVENT_TRADED, EVENT_TIMER, EVENT_POSITION
from vnpy.gateway.ctp import CtpGateway
import logging
import pdb
import datetime
from datetime import datetime
import talib
import pandas as pd
from vnpy.trader.ui import create_qapp, QtCore
from vnpy.trader.constant import Exchange, Interval
from vnpy.trader.database import database_manager
from vnpy.chart import ChartWidget, VolumeItem, CandleItem
import os
import importlib
import traceback
from datetime import datetime
from threading import Thread
from pathlib import Path
from inspect import getfile

from vnpy.event import Event, EventEngine
from vnpy.trader.engine import BaseEngine, MainEngine
from vnpy.trader.constant import Interval
from vnpy.trader.utility import extract_vt_symbol
from vnpy.trader.object import (
    HistoryRequest,
    LogData
)
from vnpy.trader.rqdata import rqdata_client
from vnpy.trader.database import database_manager
from vnpy.app.cta_strategy import CtaTemplate
from vnpy.app.cta_strategy.backtesting import (
    BacktestingEngine, OptimizationSetting, BacktestingMode
)
import time
# from vnpy.gateway.ctptest import CtptestGateway
# from vnpy.gateway.mini import MiniGateway
# from vnpy.gateway.minitest import MinitestGateway
# from vnpy.gateway.femas import FemasGateway
# from vnpy.gateway.sopt import SoptGateway
# from vnpy.gateway.sopttest import SopttestGateway
# from vnpy.gateway.sec import SecGateway
# from vnpy.gateway.uft import UftGateway
# from vnpy.gateway.hsoption import HsoptionGateway
# from vnpy.gateway.xtp import XtpGateway
# from vnpy.gateway.tora import ToraStockGateway
# from vnpy.gateway.tora import ToraOptionGateway
# from vnpy.gateway.oes import OesGateway
# from vnpy.gateway.comstar import ComstarGateway
# from vnpy.gateway.futu import FutuGateway
# from vnpy.gateway.ib import IbGateway
# from vnpy.gateway.tiger import TigerGateway
# from vnpy.gateway.tap import TapGateway
# from vnpy.gateway.da import DaGateway
# from vnpy.gateway.mt5 import Mt5Gateway
# from vnpy.gateway.binance import BinanceGateway
# from vnpy.gateway.binances import BinancesGateway
# from vnpy.gateway.huobi import HuobiGateway
# from vnpy.gateway.huobif import HuobifGateway
# from vnpy.gateway.huobis import HuobisGateway
# from vnpy.gateway.huobio import HuobioGateway
# from vnpy.gateway.okex import OkexGateway
# from vnpy.gateway.okexf import OkexfGateway
# from vnpy.gateway.okexs import OkexsGateway
# from vnpy.gateway.okexo import OkexoGateway
# from vnpy.gateway.bitmex import BitmexGateway
# from vnpy.gateway.bybit import BybitGateway
# from vnpy.gateway.gateios import GateiosGateway
# from vnpy.gateway.deribit import DeribitGateway
# from vnpy.gateway.bitfinex import BitfinexGateway
# from vnpy.gateway.coinbase import CoinbaseGateway
# from vnpy.gateway.bitstamp import BitstampGateway
# from vnpy.gateway.onetoken import OnetokenGateway
# from vnpy.gateway.rohon import RohonGateway
# from vnpy.gateway.xgj import XgjGateway
# from vnpy.gateway.alpaca import AlpacaGateway

from vnpy.app.cta_strategy import CtaStrategyApp
from vnpy.app.cta_backtester import CtaBacktesterApp
# from vnpy.app.spread_trading import SpreadTradingApp
from vnpy.app.algo_trading import AlgoTradingApp
# from vnpy.app.option_master import OptionMasterApp
# from vnpy.app.portfolio_strategy import PortfolioStrategyApp
# from vnpy.app.script_trader import ScriptTraderApp
# from vnpy.app.market_radar import MarketRadarApp
from vnpy.app.chart_wizard import ChartWizardApp
# from vnpy.app.redis_event import RedisEventApp
# from vnpy.app.chart_trader import ChartTraderApp
# from vnpy.app.can_lun import CanLunApp

# from vnpy.app.rpc_service import RpcServiceApp
# from vnpy.app.excel_rtd import ExcelRtdApp
# from vnpy.app.risk_manager import RiskManagerApp
# from vnpy.app.portfolio_manager import PortfolioManagerApp


ctp_yongan_fangzhen_setting = {
    "用户名": "101302164",
    "密码": "Binchen2021^",
    "经纪商代码": "1032",
    "交易服务器": "115.238.53.139:51207",
    "行情服务器": "115.238.53.139:51219",
    "产品名称": "client_bcpy_v0.1",
    "授权编码": "P8NE5F4XY3KDWTII",
    "产品信息": "client_bcpy_v0.1"
}
ctp_setting = {
    "用户名": "140589",
    "密码": "bc2021",
    "经纪商代码": "9999",
    "交易服务器": "180.168.146.187:10130",
    "行情服务器": "180.168.146.187:10131",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "simnow_client"
}
ctp_yongan_product_setting = {
    "用户名": "101302164",
    "密码": "Binchen2021^",
    "经纪商代码": "1032",
    "交易服务器": "122.224.221.229:41255",
    "行情服务器": "122.224.221.230:41255",
    "产品名称": "client_bcpy_v0.1",
    "授权编码": "P8NE5F4XY3KDWTII",
    "产品信息": "client_bcpy_v0.1"
}
ctp_zhongqi_product_setting = {
    "用户名": "930838",
    "密码": "YanFang2021^",
    "经纪商代码": "8070",
    "交易服务器": "101.226.253.248:21205",
    "行情服务器": "101.226.253.248:21213",
    "产品名称": "client_bcpy_v0.1",
    "授权编码": "JQEQL9YXD7MFJ76K",
    "产品信息": "client_bcpy_v0.1"
}


def main():
    """"""
    qapp = create_qapp()

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)

    main_engine.add_gateway(CtpGateway)
    # main_engine.add_gateway(CtptestGateway)
    # main_engine.add_gateway(MiniGateway)
    # main_engine.add_gateway(MinitestGateway)
    # main_engine.add_gateway(FemasGateway)
    # main_engine.add_gateway(SoptGateway)
    # main_engine.add_gateway(SopttestGateway)
    # main_engine.add_gateway(SecGateway)
    # main_engine.add_gateway(UftGateway)
    # main_engine.add_gateway(HsoptionGateway)
    # main_engine.add_gateway(XtpGateway)
    # main_engine.add_gateway(ToraStockGateway)
    # main_engine.add_gateway(ToraOptionGateway)
    # main_engine.add_gateway(OesGateway)
    # main_engine.add_gateway(ComstarGateway)
    # main_engine.add_gateway(FutuGateway)
    # main_engine.add_gateway(IbGateway)
    # main_engine.add_gateway(TigerGateway)
    # main_engine.add_gateway(TapGateway)
    # main_engine.add_gateway(DaGateway)
    # main_engine.add_gateway(Mt5Gateway)
    # main_engine.add_gateway(BinanceGateway)
    # main_engine.add_gateway(BinancesGateway)
    # main_engine.add_gateway(HuobiGateway)
    # main_engine.add_gateway(HuobifGateway)
    # main_engine.add_gateway(HuobisGateway)
    # main_engine.add_gateway(HuobioGateway)
    # main_engine.add_gateway(OkexGateway)
    # main_engine.add_gateway(OkexfGateway)
    # main_engine.add_gateway(OkexsGateway)
    # main_engine.add_gateway(OkexoGateway)
    # main_engine.add_gateway(BitmexGateway)
    # main_engine.add_gateway(BybitGateway)
    # main_engine.add_gateway(GateiosGateway)
    # main_engine.add_gateway(DeribitGateway)
    # main_engine.add_gateway(BitfinexGateway)
    # main_engine.add_gateway(CoinbaseGateway)
    # main_engine.add_gateway(BitstampGateway)
    # main_engine.add_gateway(OnetokenGateway)
    # main_engine.add_gateway(RohonGateway)
    # main_engine.add_gateway(XgjGateway)
    # main_engine.add_gateway(AlpacaGateway)

    main_engine.add_app(CtaStrategyApp)
    main_engine.add_app(CtaBacktesterApp)
    # main_engine.add_app(SpreadTradingApp)
    main_engine.add_app(AlgoTradingApp)
    # main_engine.add_app(OptionMasterApp)
    # main_engine.add_app(PortfolioStrategyApp)
    # main_engine.add_app(ScriptTraderApp)
    # main_engine.add_app(MarketRadarApp)
    main_engine.add_app(ChartWizardApp)
    # main_engine.add_app(CanLunApp)

    # main_engine.add_app(RpcServiceApp)
    # main_engine.add_app(ExcelRtdApp)
    main_engine.add_app(DataManagerApp)
    main_engine.add_app(DataRecorderApp)
    main_engine.add_app(DingMsgApp)
    # main_engine.add_app(RedisEventApp)
    # main_engine.add_app(PaperAccountApp)
    # main_engine.add_app(ChartTraderApp)
    # main_engine.add_app(RiskManagerApp)
    # main_engine.add_app(PortfolioManagerApp)
    # main_engine.add_app(PaperAccountApp)
    gw = main_engine.get_gateway("CTP")
    # gw2 = main_engine.get_gateway("CTP")
    gw.connect(ctp_setting)
 
    gw.query_position()
    gw.query_account()
    # from vnpy.event.engine import Event, EVENT_TIMER
    # event = Event(EVENT_TIMER)
    # event_engine.put(event)

    event = Event(
        EVENT_TRADE,
        "test"
    )
    event_engine.put(event)



    symbol = "IF2201"
    exchange = Exchange.CFFEX
    start=datetime(2021, 12, 1)
    end=datetime(2022, 3, 17)
    interval=Interval.MINUTE
    bars = database_manager.load_bar_data(
        symbol,
        Exchange.CFFEX,
        interval=Interval.MINUTE,
        start=start,
        end=end
    )
    if not bars or len(bars) == 0:

        req = HistoryRequest(
            symbol=symbol,
            exchange=exchange,
            interval=Interval.MINUTE,
            start=start,
            end=end
        )

        try:
            bars = rqdata_client.query_history(req)

            if bars:
                database_manager.save_bar_data(bars)
                print(f"{symbol}-{interval}历史数据下载完成")
            else:
                print(f"数据下载失败，无法获取{symbol}的历史数据")
        except Exception:
            msg = f"数据下载失败，触发异常：\n{traceback.format_exc()}"
            print(msg)
    widget = ChartWidget()
    widget.add_plot("candle", hide_x_axis=True)
    # widget.add_plot("candle2", hide_x_axis=False)
    widget.add_plot("volume", maximum_height=200)
    widget.add_item(CandleItem, "candle", "candle")
    # widget.add_item(CandleItem, "candle2", "candle2")
    widget.add_item(VolumeItem, "volume", "volume")
    widget.add_cursor()

    n = 1000
    history = bars[:n]
    new_data = bars[n:]

    widget.update_history(history)

    def update_bar():
        bar = new_data.pop(0)
        
        main_engine.event_engine.put(Event(type =EVENT_BAR, data =bar))
        widget.update_bar(bar)
    # import pandas as pd
    # df = pd.DataFrame(bars, columns=['datetime','open_price', 'high_price', 'low_price','close_price']) 
    # print(type(bars))
    # result = talib.EMA(df.close_price, 20)
    # print( result.head(3))
    timer = QtCore.QTimer()

    timer.timeout.connect(update_bar)
    timer.start(1000)

    widget.show()
 
    main_window = MainWindow(main_engine, event_engine)
    main_window.showMaximized()
    qapp.exec()


if __name__ == "__main__":
    main()
